class UserController < ApplicationController
  skip_before_filter :require_login

  def index
    @user = session[:user]
    if is_guest
      flash[:message] = 'You must login first!'
      redirect_to :action => 'login'
    end
  end

  def login
    if is_guest
      username = params[:username_lg]
      password = params[:password_lg]

      if username != nil
        user = User.find_by_username(username)
        if user != nil && user.authorise(password)
          create_user_session(user)
          flash[:message] = 'Login successfully!'
          redirect_to request.env['HTTP_REFERER'] || '/homepage/index'
        else
          flash[:message] = 'Wrong information'
        end
      end
    else
      redirect_to :action => 'index'
    end
  end

  def logout
    destroy_user_session
    redirect_to request.env['HTTP_REFERER'] || '/homepage/index'
  end

  def create
    name = params[:name_ct]
    phone = params[:phone_ct]
    address = params[:address_ct]
    email = params[:email_ct]
    username = params[:username_ct]
    password = params[:password_ct]

    if is_guest
      if name != nil
        begin
          User.create({:name => name, :phone => phone, :address => address, :email => email, :username => username, :password => password})
        rescue
          flash[:message] = 'Wrong information, please refill!'
          redirect_to :action => 'create'
        else
          flash[:message] = 'Create successfully, please login'
          redirect_to :action => 'login'
        end
      end
    else
      redirect_to :action => 'login'
    end
  end

  def info_change
    @user = session[:user]
    if is_guest
      flash[:message] = 'You must login first!'
      redirect_to :action => 'login'
    end

    name = params[:name]
    birth = params[:birt]
    sex = params[:sex]
    address = params[:address]
    phone = params[:phone]

    if birth != nil
      new_birthday = DateTime.strptime(birth, '%m-%d-%Y').to_date
    end

    if name != nil
      @user.update_attributes(:name => name, :birth => new_birthday, :sex => sex, :address => address, :phone => phone)
      redirect_to '/user/index'
    end
  end

  def password_change
    @user = session[:user]

    old_password = params[:old_password]
    new_password = params[:new_password]
    confirm_password = params[:confirm_password]
    user_id = params[:user_id]

    if is_guest
      flash[:message] = 'You must login first!'
      redirect_to :action => 'login'
    end

    if new_password != nil
      if new_password == confirm_password
        if @user.authorise(old_password)
          @user.update_attribute(:password, new_password)
          flash[:message] = 'Password changed successfully'
          redirect_to '/user/index'
        else
          flash[:message] = 'Wrong old password'
        end
      else
        flash[:message] = 'Confirm password is wrong'
      end
    end
  end
end
